import {IApi} from 'umi';
import {join, dirname} from 'path';
import {existsSync, mkdirSync, readFileSync} from 'fs';
import {winPath} from '@umijs/utils';

/**
 * 对使用的到的umi插件进行增强
 * 比如 让app.ts中的 request = ({initialState}) => ...  , 让它内部能够获取到 initialState
 * @param api
 */
export default function (api: IApi) {
    const {paths} = api;

    // 使用api.addHTMLHeadScripts方法,打包时给html文件的head中添加一个script标签和内容
    //api.addHTMLHeadScripts(() => `console.log('新添加的代码')`)
    //console.log("paths-------", paths)

    api.onGenerateFiles(() => {
        if (api.isPluginEnable('model')) {
            /**
             * 为keepalive插件 增加 initialState的支持
             */
            try {
                const pluginKeepaliveContextText = readFileSync(winPath(join(paths.absTmpPath, '/plugin-keepalive/context.tsx')), 'utf-8');

                api.writeTmpFile({
                    path: winPath(join('../plugin-keepalive', 'context.tsx')),
                    content: pluginKeepaliveContextText
                        //.replace(/(import\s+React.*\s+from\s+'react';)/, `$1\nimport { useModel } from '@@/plugin-model';`)
                        //.replace(/(const\s+element\s*=\s*useOutlet\(\s*\)\s*;)/, `$1\nconst {initialState} = useModel('@@initialState');`)
                        //.replace(/(type:\s*['"]modify['"]\s*,\s*initialValue:)\s*{\s*}/, `$1{initialState},`)
                        // .replace(/(return\s+getLocalFromClientRoutes\(clientRoutes\)\s*;[\n\s]+},\s*)\[\s*\]\)\s*;/, `$1[initialState]\);`)
                        //.replace(/return runtime;/, `return {...runtime, routes: getLocalFromClientRoutes(clientRoutes, routes)};`)
                        .replace(/initialValue: \{initialState\},/, `initialValue: {initialState, router:getLocalFromClientRoutes(clientRoutes,routes)},`)
                        //.replace("${location.pathname}::${tabNameMap[location.pathname]}", "${location.pathname}::${tabNameMap[location.pathname]}::${location.search}")
                        //.replace("navigate(path);", `const search = keepElements.current[path]?.search;navigate(path + (search?search:""));`)
                        //.replace("{name, icon, closable}", "{name, search, icon, closable}")
                        //.replace("${pathname}::${tabNameMap[pathname]}", "${pathname}::${tabNameMap[pathname]}::${search}")
                    //.replace(/const CustomTabs = getCustomTabs\(\);/, 'const CustomTabs = React.useMemo(()=>getCustomTabs(),[]);'),
                });
            } catch (e) {
            }
        }
    });
}
